package com.zdxlz.fcmp.common.security.util;


import jakarta.servlet.http.HttpServletRequest;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

public class RequestUtil {

    /**
     * @param request 请求
     * @return map
     * @description  获取请求参数
     */
    public static Map<String, String> readGetParameter(HttpServletRequest request) {

        Map<String, String> map = new HashMap<>();
        // 获取所有参数名并遍历获取每个参数的值
        Enumeration<String> parameterNames = request.getParameterNames();
        while (parameterNames.hasMoreElements()) {
            String paramName = parameterNames.nextElement();
            String[] paramValues = request.getParameterValues(paramName);
            for (String value : paramValues) {
                map.put(paramName, value);
            }
        }
        return map;
    }

    /**
     * 读取post请求体，返回json字符串
     * @param request
     * @return string json
     */
    public static String readPostBody(HttpServletRequest request) throws IOException {

        // 设置请求编码以正确解析请求体
        request.setCharacterEncoding("UTF-8");

        // 读取请求体内容
        StringBuilder sb = new StringBuilder();
        try (BufferedReader reader = request.getReader()) {
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        }
        return sb.toString();
    }
}
